package com.eking.tasks;

import java.util.Optional;

import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.eking.common.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * 定时任务
 * Created by hexp on 2023/9/6 10:28
 */
@Configuration
@EnableScheduling
@Slf4j
public class ScheduleTask {
    private String accessToken;

    @Scheduled(fixedDelay = Constant.expiration)
    private void getAccessToken() {
        Client client = createClient();
        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                .setAppKey(Constant.appKey)
                .setAppSecret(Constant.appSecret);
        try {
            GetAccessTokenResponse clientAccessToken = client.getAccessToken(getAccessTokenRequest);
            accessToken = Optional.ofNullable(clientAccessToken).map(GetAccessTokenResponse::getBody)
                    .map(GetAccessTokenResponseBody::getAccessToken).orElse("");
        } catch (Exception _err) {
            log.error("获取AccessToken失败", _err);
        }
    }

    public String getToken() {
        return accessToken;
    }

    public Client createClient() {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            log.error("创建Client失败", e);
        }
        return client;
    }
}
